package cn.tedu.csmall.product.ex.handler;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

/**
 * ClassName: GlobalExceptionHandler
 * Package: cn.tedu.csmall.product.ex.handler
 * Description 全局异常处理器
 *
 * @version 0.0.1
 * @Author: 大傻
 * @Create:2022/11/29
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e){
        return JsonResult.fail(e);
    }
    @ExceptionHandler
    public JsonResult handleBindException(BindException e){
//
//        StringJoiner stringJoiner = new StringJoiner(",","添加相册失败,","!");
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for (FieldError fieldError : fieldErrors) {
//            String defaultMessage = fieldError.getDefaultMessage();
//            stringJoiner.add(defaultMessage);
//
//        }
//       StringBuilder stringBuilder = new StringBuilder();
//        String prefix = "添加失败，";
//        String suffix = "！";
//        String defaultMessage = e.getFieldError().getDefaultMessage();
//        stringBuilder.append(prefix).append(defaultMessage).append(suffix);
        String defaultMessage = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,defaultMessage);

    }
    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e){
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        String delimiter = "，";
        StringJoiner stringJoiner = new StringJoiner(delimiter);
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
               stringJoiner.add( constraintViolation.getMessage());
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,stringJoiner.toString());
    }

}
